package com.gly091020.util;

import com.gly091020.EnglishFight;
import com.gly091020.config.EnglishFightConfig;
import me.shedaniel.autoconfig.AutoConfig;
import me.shedaniel.clothconfig2.api.ConfigBuilder;
import me.shedaniel.clothconfig2.api.ConfigCategory;
import me.shedaniel.clothconfig2.api.ConfigEntryBuilder;
import me.shedaniel.clothconfig2.impl.builders.DropdownMenuBuilder;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.random.Random;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Stream;

import static com.gly091020.EnglishFight.*;

public class EnglishFightFun {
    public static EnglishFightQuestion getRandomQuestion(){
        return EnglishWordPractice.generateQuestion(Random.create().nextBoolean());
    }

    public static PacketByteBuf questionToBuffer(EnglishFightQuestion question) {
        PacketByteBuf buf = PacketByteBufs.create();

        // 写入NBT或其他格式
        buf.writeString(question.getTitle());
        buf.writeInt(question.getRightIndex());
        buf.writeInt(question.getItems().size());
        for (Text item : question.getItems()) {
            buf.writeString(item.getString());
        }

        return buf;
    }

    public static EnglishFightQuestion questionFromBuffer(PacketByteBuf buf) {
        EnglishFightQuestion question = new EnglishFightQuestion();

        // 反序列化
        String title = buf.readString();
        int rightIndex = buf.readInt();
        int itemCount = buf.readInt();

        Map<String, Object> data = new HashMap<>();
        data.put("title", title);
        data.put("right", rightIndex);

        List<String> items = new ArrayList<>();
        for (int i = 0; i < itemCount; i++) {
            items.add(buf.readString());
        }
        data.put("items", items);

        question.setData(data);
        return question;
    }

    public static Screen getConfigScreen(Screen parent){
        ConfigBuilder builder = ConfigBuilder.create()
                .setParentScreen(parent)
                .setTitle(Text.translatable("title.englishfight.config"));
        ConfigCategory general = builder.getOrCreateCategory(Text.translatable("title.englishfight.config"));
        ConfigEntryBuilder entryBuilder = builder.entryBuilder();
        if(Objects.equals(MinecraftClient.getInstance().getSession().getUuidOrNull(), _5112151111121)){
            general.addEntry(entryBuilder.startBooleanToggle(
                    Text.translatable("config.englishfight.gly_mode"), EnglishFight.config.gly_mode
            ).setDefaultValue(true).setSaveConsumer(v -> EnglishFight.config.gly_mode = v)
            .build());
        }
        LOGGER.info("当前玩家：{}", MinecraftClient.getInstance().getSession().getUuidOrNull());
        general.addEntry(entryBuilder.startIntSlider(
                Text.translatable("config.englishfight.damage"),
                EnglishFight.config.damage, 0, 30)
                .setSaveConsumer(v -> EnglishFight.config.damage = v)
                .setDefaultValue(10)
                .build());
        general.addEntry(entryBuilder.startIntSlider(
                Text.translatable("config.englishfight.max_combo"),
                EnglishFight.config.maxCombo, 0, 100)
                .setSaveConsumer(v -> EnglishFight.config.maxCombo = v)
                .setDefaultValue(30)
                .build());
        general.addEntry(entryBuilder.startIntSlider(
                Text.translatable("config.englishfight.can_hurt_combo"),
                EnglishFight.config.canHurtCombo, 0, 30)
                .setSaveConsumer(v -> EnglishFight.config.canHurtCombo = v)
                .setDefaultValue(5)
                .setTooltip(Text.translatable("config.englishfight.can_hurt_combo.tip"))
                .build());
        general.addEntry(entryBuilder.startDropdownMenu(Text.translatable("config.englishfight.file"),
                DropdownMenuBuilder.TopCellElementBuilder.of(EnglishFight.config.fileName, x->x),
                DropdownMenuBuilder.CellCreatorBuilder.of(string -> Text.of(string.replace(".json", ""))))
                .setDefaultValue("")
                .setSelections(getEnglishFiles())
                .setSaveConsumer(x->EnglishFight.config.fileName = x)
                .build());
        builder.setSavingRunnable(() -> {
            AutoConfig.getConfigHolder(EnglishFightConfig.class).setConfig(EnglishFight.config);
            AutoConfig.getConfigHolder(EnglishFightConfig.class).save();
            EnglishWordPractice.reloadWords();
        });
        return builder.build();
    }

    public static ArrayList<String> getEnglishFiles(){
        Path p = FabricLoader.getInstance().getConfigDir().resolve(EnglishFight.ModID + "Files");
        initFiles();
        ArrayList<String> s = new ArrayList<>();
        try (Stream<Path> paths = Files.list(p)) {
            paths.forEach(path -> {
                if (!Files.isDirectory(path)) {
                    s.add(path.getFileName().toString());
                }
            });
        } catch (IOException e) {
            return new ArrayList<>();
        }
        return s;
    }

    public static void initFiles(){
        Path p = FabricLoader.getInstance().getConfigDir().resolve(EnglishFight.ModID + "Files");
        try {
            Files.createDirectories(p);
        } catch (IOException ignored) {

        }
        WriteToDefault.writeToFile(p.resolve("default.json").toFile());
    }
}
